package controllers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"github.com/pquerna/otp"
	"github.com/pquerna/otp/totp"

	"learn-otp/models"
)

type LoginController struct {
	BaseController
}

func (c *LoginController) Login() {
	obj := c.GetString("obj")

	var data map[string]string
	if err := json.Unmarshal([]byte(obj), &data); err != nil {
		c.writeError(err)
		return
	}
	accountName := data["loginId"]
	passCode := data["passcode"]

	user, err := userDao.GetUser2(accountName, "otp")
	if err != nil {
		c.Ctx.ResponseWriter.WriteHeader(http.StatusUnauthorized)
		c.writeError(err)
		return
	}

	ok, err := totp.ValidateCustom(passCode, user.Secret, time.Now(), totp.ValidateOpts{
		Digits:    otp.DigitsSix,
		Algorithm: otp.AlgorithmSHA1,
		Skew:      1,
	})
	if err != nil {
		c.Ctx.ResponseWriter.WriteHeader(http.StatusUnauthorized)
		c.writeError(err)
		return
	}

	if ok {
		c.Ctx.Input.CruSession.Set("id", passCode)
	}

	c.Data["json"] = Response{
		Success: ok,
	}

	logDao.AddLog(&models.Log{
		AccountName: accountName,
		AppName:     "otp",
		Passcode:    passCode,
		Result:      fmt.Sprint(ok),
	})

	c.ServeJSON()
}

func (c *LoginController) Logout() {
	c.DestroySession()
	c.Redirect("/", 302)
}
